<!DOCTYPE html>
<html>
<head>
    <title>Canvas Translate Rectangle</title>
</head>
<body>
    <canvas id="myCanvas" width="400" height="300" style="border:1px solid #000000;"></canvas>
    <button id="moveButton">Move Rectangle</button>

    <script>
      let canvas = document.getElementById('myCanvas');
      let ctx = canvas.getContext('2d');

      let x = 0, y = 0, width = 100, height = 50, left = 0
      let moveButton = document.getElementById('moveButton');

      function moveRect() {
        // 首先清空画布
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        // 保存当前环境的状态
        ctx.save();
        // 平移画布
        ctx.translate(left, 0);
        // 绘制矩形
        ctx.fillRect(x, y, width, height);
        // 恢复之前保存的状态
        ctx.restore();
        left += 20;

        if (left > canvas.width - width) {
          left = 0;
        }
      }
      moveRect();
      moveButton.addEventListener('click', moveRect)
    </script>
</body>
</html>